home *** CD-ROM | disk | FTP | other *** search
- Path: jaxnet.jaxnet.com!jax!garyg
- From: garyg@jax.jaxnet.com (Gary M. Greenberg)
- Newsgroups: comp.lang.c,comp.unix.programmer
- Subject: Re: Q: '\n' character
- Followup-To: comp.lang.c,comp.unix.programmer
- Date: 14 Apr 1996 22:09:10 GMT
- Organization: Southeast Network Services, Inc.
- Message-ID: <4krt26$l00@jaxnet.jaxnet.com>
- References: <4kj66f$k0o@ren.cei.net> <1996Apr11.192937.25676@sq.com> <829396473snz@genesis.demon.co.uk>
- NNTP-Posting-Host: jax.jaxnet.com
- X-Newsreader: TIN [version 1.2 PL2]
-
- Lawrence Kirby (fred@genesis.demon.co.uk) wrote:
- : In article <1996Apr11.192937.25676@sq.com> msb@sq.com "Mark Brader" writes:
-
- : >> > Is there a function or some sort of way that I could remove '\n'
- : >> > charecter form the end of the string.
- : >>
- : >> fgets(buffer, file);
- ^^^^^^^^^^^^^^^^^^^^^^
- Sorry to have missed part of this thread; but doesn't fgets() require a
- third parameter. If buffer was declared as, say, "char buffer[BUFSIZ];"
- && Assuming, of course, #include <stdio.h>, then we'd have something like:
-
- fgets(buffer,sizeof(buffer),file);
-
- : >> buffer[strlen(buffer)-1]=0;
- : >>
- : >> It may not be the fastest, but it is darned near the easiest.
- : >
- : >Or the buggiest. Instead use:
- : >
- : > len = strlen (buffer);
- : > if (len > 0 && buffer[len-1] == '\n') buffer[len-1] = '\0';
- : >
- : >Both tests in the "if" are necessary.
-
- : Not exactly true. fgets() can never place a zero length string in the
- : buffer. However its return value can be a null pointer on end-of-file or
- : failure and that condition must be tested for. fgets() will leave the buffer
- : unchanged if it encounters end-of-file but that is the only case where
- : you could legally test for and possibly find a zero length string. So the
- : code should look something like:
-
- Not to detract from the wisdom being imparted herein ...
-
- : if (fgets(buffer, file) != NULL) {
- ^^^^^^^^^^^^^^^^^^^^ seems Lawrence carried the error forward.
-
- Is this what is meant by 'inheritance' ;-)
-
- : size_t len = strlen(buffer);
-
- : if (buffer[len-1] == '\n') buffer[len-1] = '\0';
- : }
-
- : >In the specific case of a string obtained from fgets(), we can be
- : >sure that if there is a newline then it is the last character.
- : >This leads to the alternative approach:
- : >
- : > ptr = strchr (buffer, '\n'); /* or strrchr() */
- : > if (ptr) *ptr = '\0';
-
- : Or the very alternative approach:
-
- : strtok(buffer, "\n");
-
- : But in both cases you still need to test the return code of fgets().
-
- : Lawrence Kirby | fred@genesis.demon.co.uk
- ^^^^^ ^^^
- Makes ya wonder who it is? ;-}
-
- gary /* the Sorcerer's Apprentice */
- Contribute to the Randal Schwartz Legal Defense Fund
- Get FREE ANSI C E-Mail Management Source Code
- Visit: http://jax.jaxnet.com/~garyg/main_page.html
-